import { GameMapBase } from '@/assets/map/GameMapBase.js'
import { PlayerFactory } from '@/assets/player/PlayerFactory.js'
import { useUserStore } from '@/stores/user.js'
import { useWebsocketStore } from '@/stores/websocket.js'
import { FlashEffect } from '@/assets/skills/Flash.js'

/**
 * 联机对战游戏地图类，继承自GameMap基类
 * 负责管理联机对战游戏模式下的地图绘制和更新
 */
export class PvPGameMap extends GameMapBase {
    /**
     * 构造函数，初始化多人游戏地图
     * @param {CanvasRenderingContext2D} ctx - 画布2D渲染上下文
     */
    constructor(ctx) {
        super(ctx)
        this.initialize_players()
    }

    initialize_players() {
        const userStore = useUserStore()
        const websocketStore = useWebsocketStore()

        // 获取所有玩家信息并按照userId排序
        const allPlayers = [
            {
                userId: userStore.id,
                role: 'me',
                ...userStore,
            },
            ...websocketStore.pk.opponents.map((opponent) => ({ ...opponent, role: 'foe' })),
        ].sort((a, b) => {
            // 确保userId存在且为字符串
            const idA = String(a?.userId || '')
            const idB = String(b?.userId || '')
            return idA.localeCompare(idB)
        }) //按userId排序一致

        // 创建所有玩家
        for (let i = 0; i < allPlayers.length; i++) {
            const player = allPlayers[i]
            // 所有玩家初始位置都在正中心
            const x = this.width / 2
            const y = this.height / 2

            this.players.push(
                PlayerFactory.createPlayer(this, {
                    x: x,
                    y: y,
                    radius: this.height * this.sizeConfig.playerRadius,
                    color: player.role === 'me' ? 'white' : this.get_random_color(),
                    speed: this.height * this.sizeConfig.playerSpeed,
                    hp: 100,
                    role: player.role,
                    photo: player.photo,
                    username: player.username,
                    userId: player.userId,
                })
            )
        }
    }

    start() {}

    // 联机模式处理玩家移动
    handle_player_move(data) {
        const player = this.players.find((p) => p.info.userId === data.userId)
        if (player && player.info.role === 'foe') {
            // 将比例坐标转换为实际坐标
            const actualX = data.x * this.width
            const actualY = data.y * this.height
            const actualTx = data.tx * this.width
            const actualTy = data.ty * this.height

            // 先立即同步当前位置
            player.info.x = actualX
            player.info.y = actualY
            // 再设置移动目标
            player.move_to(actualTx, actualTy)
        }
    }

    // 处理火球技能
    handle_fireball(data) {
        const player = this.players.find((p) => p.info.userId === data.userId)
        if (player && player.info.role === 'foe') {
            // 将比例坐标转换为实际坐标
            const actualX = data.x * this.width
            const actualY = data.y * this.height
            const actualTx = data.tx * this.width
            const actualTy = data.ty * this.height

            // 同步玩家位置
            player.info.x = actualX
            player.info.y = actualY

            // 调用对方玩家的火球技能
            if (player.skills && player.skills.fireball) {
                player.skills.fireball.cast(actualTx, actualTy)
            }
        }
    }

    // 处理闪现技能
    handle_flash(data) {
        const player = this.players.find((p) => p.info.userId === data.userId)
        if (player && player.info.role === 'foe') {
            // 将比例坐标转换为实际坐标
            const actualX = data.x * this.width
            const actualY = data.y * this.height
            const actualTx = data.tx * this.width
            const actualTy = data.ty * this.height

            // 保存玩家原始位置用于特效
            const startX = actualX
            const startY = actualY

            // 如果包含实际闪现坐标，使用发送方提供的落点
            if (data.hasOwnProperty('actualX') && data.hasOwnProperty('actualY')) {
                // 计算实际落点
                const actualDestX = data.actualX * this.width
                const actualDestY = data.actualY * this.height

                try {
                    // 显示起始位置的消失特效
                    new FlashEffect(this, startX, startY, player.info.radius, true)

                    // 直接更新玩家位置到实际落点
                    player.info.x = actualDestX
                    player.info.y = actualDestY

                    // 显示目标位置的出现特效
                    new FlashEffect(this, actualDestX, actualDestY, player.info.radius, false)

                    // 重置移动状态
                    player.moveLength = 0
                } catch (error) {
                    console.error('创建闪现特效出错:', error)
                    // 出错时使用原来的方式
                    player.info.x = startX
                    player.info.y = startY
                    if (player.skills && player.skills.flash) {
                        player.skills.flash.cast(actualTx, actualTy)
                    }
                }
            } else {
                // 如果没有实际闪现坐标，使用旧逻辑
                // 同步玩家位置
                player.info.x = actualX
                player.info.y = actualY

                // 调用对方玩家的闪现技能
                if (player.skills && player.skills.flash) {
                    player.skills.flash.cast(actualTx, actualTy)
                }
            }
        }
    }

    // 处理治疗技能
    handle_heal(data) {
        const player = this.players.find((p) => p.info.userId === data.userId)
        if (player && player.info.role === 'foe') {
            // 调用对方玩家的治疗技能
            if (player.skills && player.skills.heal) {
                player.skills.heal.cast()
            }
        }
    }
}
